package com.tange.ai.iot.client.gnssa.binding

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.util.Consumer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityWifiConfigurationBinding
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.feature.binding.prepare.DeviceBindingConfiguration
import com.tange.feature.binding.search.DeviceBindingSearchWiFi

class BindingConfigureActivity: AppCompatActivity() {

    companion object {
        const val TAG = "BindingConfigureActivity_"
        const val CONFIG = "binding_configuration"
    }

    private lateinit var binding: ActivityWifiConfigurationBinding

    private lateinit var wifiSearch: DeviceBindingSearchWiFi

    private var listAdapter: WiFiListAdapter? = null

    private var loading: BasicDialogLoading? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityWifiConfigurationBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
        }

        com.tange.ai.iot.client.gnssa.utils.Utils.setStatusBar(this, Color.TRANSPARENT)



        binding.next.setOnClickListener {
            create()
        }

        listAdapter = WiFiListAdapter()
        listAdapter?.onSelected = Consumer<String> {
            binding.wifiName.setText(it)
        }

        binding.wifiList.adapter = listAdapter
        binding.wifiList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        wifiSearch = DeviceBindingSearchWiFi(this) {
            if (it.success) {
                listAdapter?.refreshApList(it.data)
            } else {
                Toast.makeText(this@BindingConfigureActivity, "扫描失败：${it.code}, ${it.message}", Toast.LENGTH_LONG).show()
            }
        }

        wifiSearch.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        wifiSearch.stop()
    }

    private fun create() {
        val ssid = binding.wifiName.text.toString().trim()
        val pwd = binding.wifiPwd.text.toString().trim()

        if (TextUtils.isEmpty(ssid)) {
            Toast.makeText(this, "Empty SSID", Toast.LENGTH_LONG).show()
            return
        }

        if (loading?.isShowing == true) {
            loading?.dismiss()
        }

        loading = BasicDialogLoading(this).apply {
            setMessage("正在生成绑定配置信息...")
        }
        loading?.show()

        DeviceBindingConfiguration.create(ssid, pwd) { configure ->
            loading?.dismiss()
            if (configure.success) {
                Intent().apply {
                    putExtra(CONFIG, configure.data)
                }.also {
                    setResult(RESULT_OK, it)
                    finish()
                }
            } else {
                BasicDialogRequest(this).apply {
                    setMessage("生成绑定配置信息失败：${configure.message}")
                    setPositiveText("知道了")
                    setPositiveOnClicked {
                        dismiss()
                        setResult(RESULT_CANCELED)
                        finish()
                    }
                }.show()
            }
        }
    }
}

class WiFiListAdapter : RecyclerView.Adapter<WiFiViewHolder>() {

    private val apList: MutableList<String> = ArrayList()

    var onSelected: Consumer<String>? = null

    fun refreshApList(list: List<String>?) {
        apList.clear()
        list?.let { apList.addAll(it) }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): WiFiViewHolder {
        val view: View = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_scan_ap, viewGroup, false)
        return WiFiViewHolder(view)
    }

    override fun onBindViewHolder(viewHolder: WiFiViewHolder, position: Int) {
        val apName = apList[position]
        viewHolder.textView.text = apName

        viewHolder.itemView.setOnClickListener { view: View ->
            onSelected?.accept(apName)
        }
    }

    override fun getItemCount(): Int {
        return apList.size
    }
}

class WiFiViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    val textView: TextView

    init {
        textView = view.findViewById(R.id.ap_name)
    }
}

